import turbogears          as tg
import cherrypy

from turbogears            import identity
from whatwhat.model        import Project, status_codes, impact_codes, chance_codes
from whatwhat              import utils
from whatwhat.widgets      import widgets



class RecentChangesController(identity.SecureResource):
    require = identity.not_anonymous()
    
    @tg.expose(template="whatwhat.templates.recentchanges.index")
    def index(self):  
        utils.checkIdentity(cherrypy.request.identity.user)      
        all_projects = Project.select("parent_project_id is NULL order by upper(name)")
        
        projects = [project for project in all_projects if not project.archived]
        
        recent_proj = utils.getRecentChanges(projects, self._timeframe())
        
        return dict(active_section='recentchanges',
                    recent_proj=recent_proj,
                    status_codes=status_codes,
                    chance_codes=chance_codes,
                    impact_codes=impact_codes,
                    time_hours=self._timeframe(),
                    questions_widget=widgets.questions_widget,
                    issues_widget=widgets.issues_widget,
                    risks_widget=widgets.risks_widget,
                    notes_widget=widgets.notes_widget)
    
    
    @tg.expose()    
    def change_time(self, change_hours):
        cherrypy.response.simpleCookie['time_frame_id'] = change_hours
        cherrypy.response.simpleCookie['time_frame_id']['path'] = '/'
        
        raise tg.redirect('/recentchanges')
        
    
    def _timeframe(self):
        if cherrypy.request.simpleCookie.has_key('time_frame_id'):
            return int(cherrypy.request.simpleCookie['time_frame_id'].value)
        return 24
